package com.mjk.common.util;


import com.mjk.common.tools.logger.BizLogger;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

import java.util.Objects;

/***
 * 作用：汉子字符串，转拼音
 * 
 * @author jafe
 *
 */
public class CharactersToPinYin {
	/**
	 * @param src
	 *            中文汉字
	 * @return 拼音
	 */
	public static String getPinYin(String src) {
		char[] t1;
		t1 = src.toCharArray();
		String[] t2;
		// 设置汉字拼音输出的格式
		HanyuPinyinOutputFormat t3 = new HanyuPinyinOutputFormat();
		t3.setCaseType(HanyuPinyinCaseType.LOWERCASE);
		t3.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
		t3.setVCharType(HanyuPinyinVCharType.WITH_V);
		StringBuilder t4 = new StringBuilder();

		try {
            for (char c : t1) {
                // 判断能否为汉字字符
                if (Character.toString(c).matches("[\\u4E00-\\u9FA5]+")) {
                    t2 = PinyinHelper.toHanyuPinyinStringArray(c, t3);// 将汉字的几种全拼都存到t2数组中
                    t4.append(t2[0]).append(" ");// 取出该汉字全拼的第一种读音并连接到字符串t4后
                } else {
                    // 如果不是汉字字符，间接取出字符并连接到字符串t4后
                    t4.append(c);
                }
            }
		} catch (BadHanyuPinyinOutputFormatCombination e) {
			throw Objects.requireNonNull(BizLogger.info(e));
		}
		return t4.toString().replace(" ", "");
	}

	/**
	 * 获取字符每个汉字的首字母
	 */
	public static String getPinYinInitials(String src) {
		if (ObjectUtils.isEmpty(src)) {
			return "";
		}

		StringBuilder initials = new StringBuilder();
		HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
		format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
		format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
		format.setVCharType(HanyuPinyinVCharType.WITH_V);

		for (char c : src.toCharArray()) {
			// 判断是否为汉字字符或字母
			if (Character.isLetter(c) && Character.UnicodeScript.of(c) == Character.UnicodeScript.HAN) {
				try {
					String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(c, format);
					if (pinyinArray != null && pinyinArray.length > 0) {
						initials.append(pinyinArray[0].charAt(0));
					}
				} catch (BadHanyuPinyinOutputFormatCombination e) {
					throw new RuntimeException("Error converting character to Pinyin", e);
				}
			} else if (Character.isLetter(c) || Character.isDigit(c)) {
				// 直接添加字母和数字
				initials.append(c);
			}
			// 其他特殊字符会被忽略
		}
		return initials.toString();
	}

}